package com.naiterui.ehp.bs.search.service.impl;

import com.naiterui.common.redis.RedisUtil;
import com.naiterui.common.repository.page.PageParamVO;
import com.naiterui.common.repository.page.PageVO;
import com.naiterui.ehp.bp.constants.CommonConstant;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.support.utils.JsonMapper;
import com.naiterui.ehp.bp.utils.thread.ThreadPoolUtil;
import com.naiterui.ehp.bs.search.config.EsProperties;
import com.naiterui.ehp.bs.search.entity.DiagnosisGb95;
import com.naiterui.ehp.bs.search.entity.SearchDrStandardDiagnosis;
import com.naiterui.ehp.bs.search.repository.mysql.DiagnosisGb95Repository;
import com.naiterui.ehp.bs.search.repository.mysql.ISearchDrStandardDiagnosisRepository;
import com.naiterui.ehp.bs.search.service.IDrDiagnosisService;
import com.naiterui.ehp.bs.search.service.impl.core.EsIndexService;
import com.naiterui.ehp.bs.search.service.impl.core.EsIndicesService;
import com.naiterui.ehp.bs.search.service.impl.core.EsSearchService;
import com.naiterui.ehp.bs.search.utils.PropertyValueConstants;
import com.naiterui.ehp.bs.search.vo.DiagnosisIndexVO;
import com.naiterui.ehp.bs.search.vo.DiagnosisVO;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.lucene.search.function.FieldValueFactorFunction;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FieldValueFactorFunctionBuilder;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Service
public class SearchDrDiagnosisServiceImpl implements IDrDiagnosisService {

    // 日志LOGGER
    private static final Logger LOGGER = LoggerFactory.getLogger(SearchDrDiagnosisServiceImpl.class);
    // 默认读取数据页码
    private static final int PAGE = 1;
    // 默认读取数据每页条数
    private static final int NUM = 50000;

    // 诊断索引的名称-标准库
    private static final String INDEX_NAME_STANDARD = "diagnosis_standard";
    // 诊断索引的名称-GB95
    private static final String INDEX_NAME_GB95 = "diagnosis_gb95";
    // 单处方逻辑最大药品数，为保证性能如果skuId大于10则只取前10(正常单张处方药品数应不大于5)
    private static final Integer DIAGNOSIS_MAX_SKU = 10;
    // 单诊断基础分值
    private static final float DIAGNOSIS_SINGLE_POINT = 1.50f;
    // 单诊断最大分值
    private static final float DIAGNOSIS_SINGLE_POINT_MAX = 4.50f;

    private static String CHINESE_UNICODE_PATTERN = "[\\u4e00-\\u9fa5]+";

    @Autowired
    private EsProperties esProperties;
    @Autowired
    private EsIndexService esIndexService;
    @Autowired
    private EsIndicesService esIndicesService;
    @Autowired
    private EsSearchService esSearchService;
    @Autowired
    private ISearchDrStandardDiagnosisRepository standardDiagnosisRepository;
    @Autowired
    private DiagnosisGb95Repository diagnosisGb95Repository;

    // 创建索引的settings配置
    private XContentBuilder getIndexSettings() throws IOException {
        XContentBuilder settings = XContentFactory.jsonBuilder()
                .startObject()
                .field("index.number_of_shards", EsIndicesService.INDEX_NUMBER_OF_SHARDS)
                .field("index.number_of_replicas", esProperties.getReplicasNum())
                .startObject("analysis")
                .startObject("analyzer")
                .startObject("default")
                .field("tokenizer", "ik_max_word")
                .endObject()
                .startObject("pinyin_analyzer")
                .field("tokenizer", "my_pinyin")
                .endObject()
                .endObject()
                .startObject("tokenizer")
                .startObject("my_pinyin")
                .field("type", "pinyin")
                .field("keep_separate_first_letter", "false")
                .field("keep_full_pinyin", "true")
                .field("keep_original", "true")
                .field("limit_first_letter_length", "16")
                .field("lowercase", "true")
                .field("remove_duplicated_term", "true")
                .endObject()
                .endObject()
                .endObject()
                .endObject();
        return settings;
    }

    // 创建索引type的mapping配置
    private XContentBuilder getMapping() throws IOException {
        // ik分词器（ik_smart\ik_max_word）ik_smart导致缩写诊断无法被检索，ik_max_word导致完全匹配结果由于分词问题不能准确靠前
        XContentBuilder mappings = XContentFactory.jsonBuilder()
                .startObject()
                .startObject("properties")
                .startObject("name")
                .field("type", "keyword")
                .startObject("fields")
                .startObject("primitive")
                .field("type", "text")
                .field("store", "true")
                .field("search_analyzer", "ik_smart")
                .field("analyzer", "ik_max_word")
                .endObject()
                .startObject("pinyin")
                .field("type", "text")
                .field("store", "false")
                .field("term_vector", "with_offsets")
                .field("analyzer", "pinyin_analyzer")
                .endObject()
                .endObject()
                .endObject()
                .startObject("commonKeywords")
                .field("type", "text")
                .field("store", "false")
                .field("search_analyzer", "ik_smart")
                .field("analyzer", "ik_max_word")
                .endObject()
                .startObject("alias")
                .field("type", "text")
                .field("store", "false")
                .field("search_analyzer", "ik_smart")
                .field("analyzer", "ik_max_word")
                .endObject()
                .endObject()
                .endObject();
        return mappings;
    }

    @Override
    public long findStardandDiagnosisIndex() throws BusinessException {
        // 1.判断索引是否存在，如果不存在则创建索引
        boolean indexExists = esIndicesService.indexExists(INDEX_NAME_STANDARD);
        if (!indexExists) {
            try {
                esIndicesService.createIndexSetSource(INDEX_NAME_STANDARD, this.getIndexSettings(), this.getMapping());
            } catch (IOException e) {
                LOGGER.error(e.getMessage(), e);
            }
        }

        // 3.分页查询标准库数据，并创建记录
        int count = 0;
        Page<SearchDrStandardDiagnosis> standardVO = standardDiagnosisRepository.findAll(new PageParamVO(PAGE, NUM).getPageable());
        for (int i = PAGE; i <= standardVO.getTotalPages(); i++) {
            // 创建索引记录
            this.createOrUpdateStandardIndex(standardVO);
            LOGGER.info("分页创建标准诊断库索引P1:" + i + "/" + standardVO.getTotalPages());
            count += standardVO.getContent().size();
            if (i < standardVO.getTotalPages()) {
                standardVO = standardDiagnosisRepository.findAll(new PageParamVO(i + 1, NUM).getPageable());
            }
        }
        return count;
    }

    @Override
    public long findDiagnosisGb95Index() throws BusinessException {
        // 1.判断索引是否存在，如果不存在则创建索引
        boolean indexExists = esIndicesService.indexExists(INDEX_NAME_GB95);
        if (!indexExists) {
            try {
                esIndicesService.createIndexSetSource(INDEX_NAME_GB95, this.getIndexSettings());
            } catch (IOException e) {
                LOGGER.error(e.getMessage(), e);
            }
        }

        // 3.分页查询标准库数据，并创建记录
        int count = 0;
        Page<DiagnosisGb95> drDiagnosisGb95s = diagnosisGb95Repository.findAll(new PageParamVO(PAGE, NUM).getPageable());
        LOGGER.info("查询到GB95索引记录数 :{}", drDiagnosisGb95s.getTotalElements());
        for (int i = PAGE; i <= drDiagnosisGb95s.getTotalPages(); i++) {
            // 创建索引记录
            this.createOrUpdateGb95Index(drDiagnosisGb95s);
            LOGGER.info("分页创建标准诊断库索引P1:" + i + "/" + drDiagnosisGb95s.getTotalPages());
            count += drDiagnosisGb95s.getContent().size();
            if (i < drDiagnosisGb95s.getTotalPages()) {
                drDiagnosisGb95s = diagnosisGb95Repository.findAll(new PageParamVO(i + 1, NUM).getPageable());
            }
        }
        return count;
    }

    private void createOrUpdateStandardIndex(final Page<SearchDrStandardDiagnosis> standardVO) {
        if (standardVO == null || standardVO.getContent().size() < 1) {
            LOGGER.info("标准诊断数据结果集为空");
            return;
        }

        ThreadPoolUtil.execute(() -> {

            BulkRequest bulkRequest = new BulkRequest();

            // 逐条组装记录
            standardVO.getContent().forEach(diagnosis -> {
                DiagnosisIndexVO vo = new DiagnosisIndexVO(diagnosis.getId(), diagnosis.getName(), diagnosis.getAlias(),
                        diagnosis.getCommonKeywords(), diagnosis
                        .getMainCode(), diagnosis.getAttachCode(), diagnosis.getWeightDef(), diagnosis.getWeightCustom());
                String source = JsonMapper.toJson(vo);
                bulkRequest.add(new UpdateRequest(INDEX_NAME_STANDARD, String.valueOf(diagnosis.getId())).doc(source,
                        XContentType.JSON).docAsUpsert(true));
            });

            BulkResponse bulkResponse = null;
            try {
                bulkResponse = esIndexService.bulkOperation(INDEX_NAME_STANDARD, bulkRequest);
                if (bulkResponse.hasFailures()) {
                    LOGGER.error("标准诊断索引插入数据失败！");
                }
            } catch (BusinessException e) {
                LOGGER.warn("标准诊断索引插入数据异常！indexName:{}", INDEX_NAME_STANDARD, e);
            }
        });
    }

    private void createOrUpdateGb95Index(final Page<DiagnosisGb95> standardVO) {
        if (standardVO == null || standardVO.getContent().size() < 1) {
            LOGGER.info("标准诊断数据结果集为空");
            return;
        }

        //ThreadPoolUtil.execute(() -> {

        BulkRequest bulkRequest = new BulkRequest();

        // 逐条组装记录
        standardVO.getContent().forEach(diagnosis -> {
            DiagnosisIndexVO vo = new DiagnosisIndexVO(diagnosis.getId(), diagnosis.getMainCode(), diagnosis.getName());
            String source = JsonMapper.toJson(vo);
            bulkRequest.add(new UpdateRequest(INDEX_NAME_GB95, String.valueOf(diagnosis.getId())).doc(source,
                    XContentType.JSON).docAsUpsert(true));
        });

        BulkResponse bulkResponse = null;
        try {
            bulkResponse = esIndexService.bulkOperation(INDEX_NAME_GB95, bulkRequest);
            if (bulkResponse.hasFailures()) {
                LOGGER.error("GB95诊断索引插入数据失败！");
            }
        } catch (BusinessException e) {
            LOGGER.warn("GB95诊断索引插入数据成功！indexName:{}", INDEX_NAME_GB95, e);
        }
        //});
    }

    @Override
    public PageVO<DiagnosisVO> searchDiagnosisList(Long doctorId, String key, List<Long> skuIds, PageParamVO paramVo) throws BusinessException {
        // 构造查询条件
        BoolQueryBuilder bq = QueryBuilders.boolQuery();
        if (doctorId != null) {
            // 过滤医生id
            bq.filter(QueryBuilders.termsQuery("doctorId", new Long[]{doctorId, 0L}));
        }
        // 关键字匹配（中文字符）
        Pattern chinesePattern = Pattern.compile(CHINESE_UNICODE_PATTERN);
        Matcher match = chinesePattern.matcher(key);
        String searchFiled = "name.pinyin";
        if (match.find() && match.group(0).equals(key)) {
            searchFiled = "name.primitive";
        }
        MultiMatchQueryBuilder multiMatchQueryBuilder =
                new MultiMatchQueryBuilder(key, searchFiled, "alias", "commonKeywords").minimumShouldMatch("90%");
        multiMatchQueryBuilder.field("name", 1.5f);
        multiMatchQueryBuilder.field("alias", 0.8f);
        multiMatchQueryBuilder.field("commonKeywords", 0.2f);
        bq.must(multiMatchQueryBuilder);
        // bq.must(QueryBuilders.multiMatchQuery(key, searchFiled, "alias^0.8", "commonKeywords^0.2"));
        // bq.should(QueryBuilders.constantScoreQuery(QueryBuilders.matchQuery("name.primitive", "流行性感冒").boost(2f)));

        // 医生的常用诊断计算分数权重加大
        //FunctionScoreQueryBuilder fsq = QueryBuilders.functionScoreQuery(bq);

        List<FunctionScoreQueryBuilder.FilterFunctionBuilder> fbs = new ArrayList<>();

        if (doctorId != null) {
            fbs.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termsQuery("idType",
                    this.findCommonDiagnosis(doctorId)), ScoreFunctionBuilders.weightFactorFunction(0.12f)));
        }
        //fsq.add(QueryBuilders.termsQuery("idType", this.findCommonDiagnosis(doctorId)), ScoreFunctionBuilders.weightFactorFunction(0.12f));

        // 获取药品适应症关键词出现次数
        Map<String, Integer> diagnosisCount = this.countSkuIdDiagnosis(skuIds);
        diagnosisCount.forEach((k, v) -> {
            Float weight = v * DIAGNOSIS_SINGLE_POINT;
            weight = weight > DIAGNOSIS_SINGLE_POINT_MAX ? DIAGNOSIS_SINGLE_POINT_MAX : weight;
            fbs.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("name.primitive", k),
                    ScoreFunctionBuilders.weightFactorFunction(weight)));
            //fsq.add(QueryBuilders.termQuery("name.primitive", k), ScoreFunctionBuilders.weightFactorFunction(weight));
            LOGGER.info("诊断关键字权重提升 doctorId:{}, key:{}, skuIds:{}, name:{}, weight:{}", doctorId, key, skuIds, k, weight);
        });

        // 根据字段值动态加权
        // 设置用来计算的字段
        FieldValueFactorFunctionBuilder fieldValueFactorCustom = new FieldValueFactorFunctionBuilder("weightCustom");
        // 设置因子
        fieldValueFactorCustom.factor(3f);
        // 缺失默认
        fieldValueFactorCustom.missing(1);
        // 用来设置计算方式，平滑曲线(new_score = old_score * log(2 + 字段值))
        fieldValueFactorCustom.modifier(FieldValueFactorFunction.Modifier.LOG2P);

        fbs.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(fieldValueFactorCustom));
        //fsq.add(fieldValueFactorCustom);

        // 设置用来计算的字段
        FieldValueFactorFunctionBuilder fieldValueFactorDef = new FieldValueFactorFunctionBuilder("weightDef");
        // 设置因子(大于1会提升效果，小于1会降低效果)
        fieldValueFactorDef.factor(3f);
        // 缺失默认
        fieldValueFactorDef.missing(1);
        // 用来设置计算方式
        fieldValueFactorDef.modifier(FieldValueFactorFunction.Modifier.LN2P);

        //fsq.add(fieldValueFactorDef);
        fbs.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(fieldValueFactorDef));

        FunctionScoreQueryBuilder fsq = QueryBuilders.functionScoreQuery(bq,
                fbs.toArray(new FunctionScoreQueryBuilder.FilterFunctionBuilder[fbs.size()]));

        fsq.boostMode(CombineFunction.SUM);
        // 设置函数最大影响
        fsq.maxBoost(6f);

        // 构造查询请求
        SearchRequest searchRequest = new SearchRequest(INDEX_NAME_STANDARD);
        SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.searchSource();

        // 设置查询条件和分页参数
        int start = (paramVo.getPage() - 1) * paramVo.getNum();
        searchSourceBuilder.query(fsq);
        searchSourceBuilder.from(start);
        searchSourceBuilder.size(paramVo.getNum());
        searchSourceBuilder.sort(SortBuilders.scoreSort());
        searchRequest.source(searchSourceBuilder);

        LOGGER.debug("search query: {}", searchRequest.toString());
        // 获取返回值，并进行处理
        SearchResponse response = esSearchService.search(searchRequest);
        SearchHits shs = response.getHits();
        List<DiagnosisVO> list = new ArrayList<>();
        for (SearchHit hit : shs) {
            DiagnosisVO vo = new DiagnosisVO();
            vo.setId(new Long((Integer) (hit.getSourceAsMap().get("id"))));
            vo.setName((String) hit.getSourceAsMap().get("name"));
            vo.setType(Integer.parseInt(hit.getSourceAsMap().get("idType").toString().split("-")[1]));
            String mainCode = (String) hit.getSourceAsMap().get("mainCode");
            String attachCode = (String) hit.getSourceAsMap().get("attachCode");
            vo.setMainCode(mainCode == null ? "" : mainCode);
            vo.setAttachCode(attachCode == null ? "" : attachCode);
            vo.setScore(hit.getScore());
            Integer weightCustom = (Integer) hit.getSourceAsMap().get("weightCustom");
            vo.setWeightCustom(weightCustom);
            Integer weightDef = (Integer) hit.getSourceAsMap().get("weightDef");
            vo.setWeightDef(weightDef);
            list.add(vo);
        }
        // 拼装分页返回值
        return PageVO.newBuilder().pageNo(paramVo.getPage()).pageSize(paramVo.getNum()).totalCount((int) shs.getTotalHits().value).result(list).build();
    }

    @Override
    public PageVO<DiagnosisVO> searchDiagnosisGb95List(String key, PageParamVO paramVo) throws BusinessException {
        // 构造查询条件
        BoolQueryBuilder bq = QueryBuilders.boolQuery();
        // 关键字匹配（中文字符）
        Pattern chinesePattern = Pattern.compile(CHINESE_UNICODE_PATTERN);
        Matcher match = chinesePattern.matcher(key);
        String searchFiled = "name.pinyin";
        if (match.find() && match.group(0).equals(key)) {
            searchFiled = "name.primitive";
        }
        MultiMatchQueryBuilder multiMatchQueryBuilder =
                new MultiMatchQueryBuilder(key, searchFiled).minimumShouldMatch("100%");
        multiMatchQueryBuilder.field("name", 1.5f);
        bq.must(multiMatchQueryBuilder);

        List<FunctionScoreQueryBuilder.FilterFunctionBuilder> fbs = new ArrayList<>();

        FunctionScoreQueryBuilder fsq = QueryBuilders.functionScoreQuery(bq, fbs.toArray(new FunctionScoreQueryBuilder.FilterFunctionBuilder[fbs.size()]));

        fsq.boostMode(CombineFunction.SUM);
        // 设置函数最大影响
        fsq.maxBoost(6f);

        // 构造查询请求
        SearchRequest searchRequest = new SearchRequest(INDEX_NAME_GB95);
        SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.searchSource();

        // 设置查询条件和分页参数
        int start = (paramVo.getPage() - 1) * paramVo.getNum();
        searchSourceBuilder.query(fsq);
        searchSourceBuilder.from(start);
        searchSourceBuilder.size(paramVo.getNum());
        searchSourceBuilder.sort(SortBuilders.scoreSort());
        searchRequest.source(searchSourceBuilder);

        LOGGER.debug("search query: {}", searchRequest.toString());
        // 获取返回值，并进行处理
        SearchResponse response = esSearchService.search(searchRequest);
        SearchHits shs = response.getHits();
        List<DiagnosisVO> list = new ArrayList<>();
        for (SearchHit hit : shs) {
            DiagnosisVO vo = new DiagnosisVO();
            vo.setId(new Long((Integer) (hit.getSourceAsMap().get("id"))));
            vo.setName((String) hit.getSourceAsMap().get("name"));
            vo.setType(Integer.parseInt(hit.getSourceAsMap().get("idType").toString().split("-")[1]));
            String mainCode = (String) hit.getSourceAsMap().get("mainCode");
            vo.setMainCode(mainCode == null ? "" : mainCode);
            vo.setScore(hit.getScore());
            list.add(vo);
        }
        // 拼装分页返回值
        return PageVO.newBuilder().pageNo(paramVo.getPage()).pageSize(paramVo.getNum()).totalCount((int) shs.getTotalHits().value).result(list).build();
    }

    /**
     * 计算药品适应症关键词出现次数
     *
     * @param skuIds
     * @return K:适应症, V:出现次数
     */
    private Map<String, Integer> countSkuIdDiagnosis(List<Long> skuIds) {

        Map<String, Integer> skuKeywordCountMap = new HashMap<>();

        int maxSku = skuIds.size() > DIAGNOSIS_MAX_SKU ? DIAGNOSIS_MAX_SKU : skuIds.size();
        for (int i = 0; i < maxSku; i++) {
            Long skuId = skuIds.get(i);
            Set<String> medicIndicationKeywordSet = RedisUtil.hashOps().hgetObject(PropertyValueConstants.REDIS_MEDIC_DIAGNOSIS_KEY, skuId + "");
            if (medicIndicationKeywordSet == null) {
                continue;
            }
            medicIndicationKeywordSet.forEach(k -> {
                if (skuKeywordCountMap.containsKey(k)) {
                    int count = skuKeywordCountMap.get(k) + 1;
                    skuKeywordCountMap.put(k, count);
                } else {
                    skuKeywordCountMap.put(k, 1);
                }
            });
        }
        return skuKeywordCountMap;
    }

    private Set<String> findCommonDiagnosis(Long doctorId) {
        // 1 迭代处理诊断，帅选出自定义诊断
        String redisKey = this.getTopDiagnosisKey(doctorId);
        return RedisUtil.zsetOps().zrevrange(redisKey, 0, 99);
    }

    private String getTopDiagnosisKey(Long doctorId) {
        return CommonConstant.REDIS_PRE_DR + "top_diagnosis_" + doctorId;
    }

}
